//
//  ZDHomeViewController.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/10/26.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

enum ZDStatusCellReuseIdentifier: String {
    
    case normalCell = "ZDNormalCell"
    case forwardCell = "ZDForwardCell"
}

class ZDHomeViewController: ZDBaseTableViewController {
    
    
    //MARK: - 懒加载微博模型数组
    var statuses: [ZDStatus]? {
    
        didSet{
        
            tableView.reloadData()
        }
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //如果没有登录 直接返回
        if !ZDAccount.isLogin {
        
            return
        }
        
        prepareUI()
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "pictureViewCellSelected:", name: ZDPictureViewCellSelectedNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "popoverViewControllerDismiss", name: ZDPopoverViewControllerDismissNotification, object: nil)
    }
    
    //注销通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //MARK: - 通知回调方法
    func pictureViewCellSelected(notification: NSNotification) {
    
//        print(notification)
        
//        let userInfo = notification.userInfo!
//        
//        let index = userInfo[ZDPictureViewCellSelectedIndexPathKey] as! Int
//        let URLs = userInfo[ZDPictureViewCellStatusURLKey] as! [NSURL]
        
        guard let index = notification.userInfo?[ZDPictureViewCellSelectedIndexPathKey] as? Int else {
        
            return
        }
        
        guard let models = notification.userInfo?[ZDPictureViewCellStatusModelKey] as? [ZDPhotoBrowserModel] else {
        
            return
        }
        
        let pbVC = ZDPhotoBrowserViewController(index: index, models: models)
        
        
        //设置转场代理
        pbVC.transitioningDelegate = pbVC
        
        //设置modal展示样式
        pbVC.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        //modal出来
        self.presentViewController(pbVC, animated: true, completion: nil)
        
    }
    
    
    func popoverViewControllerDismiss() {
    
        let btn = navigationItem.titleView as! ZDNaviTitleButton
        
        naviTitleButtonClick(btn)
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
    
        setNavigationBar()
        
        setTableView()
        
        setRefreshControl()
        
        setPulldownTipView()
    }
    
    //MARK: - 设置NavigationBar
    private func setNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        let button = ZDNaviTitleButton()
        
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        
        button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        
        // ?? 前面的表达式有值就直接返回  没有值就返回 ?? 后面的表达式结果
        let name = ZDAccount.loadAccountData()?.name ?? "没有昵称"
        
        button.setTitle(name, forState: UIControlState.Normal)
     
        //设置根据内容调整frame
        button.sizeToFit()
        
        navigationItem.titleView = button
        
        button.addTarget(self, action: "naviTitleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    //MARK: - 设置tableView
    private func setTableView() {
        
        tableView.tableFooterView = activity
        
        //设置预估高度 ———— 据说 影响性能 滚动时会有卡顿的感觉？
        tableView.estimatedRowHeight = 300
        
        //自动计算行高 ———— 当子控件约束动态改变时，系统自动计算的行高不准确 所以不能再使用系统的自动计算行高
        //这里考虑cell自己根据子控件的布局情况提供自己的高度
        //        tableView.rowHeight = UITableViewAutomaticDimension
        
        //隐藏系统分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //注册cell
        tableView.registerClass(ZDForwardCell.self, forCellReuseIdentifier: ZDStatusCellReuseIdentifier.forwardCell.rawValue)
        
        tableView.registerClass(ZDNormalCell.self, forCellReuseIdentifier: ZDStatusCellReuseIdentifier.normalCell.rawValue)
    }
    
    //MARK: - 设置refreshControl
    private func setRefreshControl() {

        refreshControl = ZDRefreshControl()
        
        //为refreshControl添加ValueChanged事件  只有当下拉到系统控件开始animating时才触发
        refreshControl?.addTarget(self, action: "loadStatuses", forControlEvents: UIControlEvents.ValueChanged)
        
        //设置一进来就开始刷新 该方法只是让控件进入刷新状态，并不会触发valueChanged方法
        refreshControl?.beginRefreshing()
        
        //代码触发ValueChanged事件 ———— 注意beginRefreshing只是进入刷新状态 开始刷新数据 并不会触发ValueChanged
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    //MARK: - 设置下拉刷新结束提示view
    private func setPulldownTipView() {
    
        //navigationBar的高度是44，加上状态栏的高度20
        pulldownTipView.frame = CGRect(x: 0, y: -20-44, width: UIScreen.width, height: 44)
        
//        navigationController?.navigationBar.addSubview(pulldownTipView)
        navigationController?.navigationBar.insertSubview(pulldownTipView, atIndex: 0)
    }
    
    
    //MARK: - 标题按钮点击事件
    //@objc 增加该属性修饰
    @objc private func naviTitleButtonClick(button: ZDNaviTitleButton) {
    
        button.selected = !button.selected
        
        //UIView旋转角度：就近原则
        //旋转角度设置 小于M_PI一点  实现逆时针转回来
        let transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI) - 0.01) : CGAffineTransformIdentity
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            button.imageView?.transform = transform
        }
        
        //如果按钮被选中 modal出控制器
        if button.selected {
        
            let popoverVC = ZDPopoverViewController.popoverViewController()
            
            //设置转场代理
            popoverVC.transitioningDelegate = self
            
            //设置转场样式
            //UIModalPresentationStyle 与 UIModalTransitionStyle有什么区别？
            //设置modal样式 则根控制器不会释放  如果不设置，根控制器会释放
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Custom
            
            //modal出来
            self .presentViewController(popoverVC, animated: true, completion: nil)
        }
    }

    
    //MARK: - 下拉刷新结束提示view动画
    private func showPulldownTipView(count: Int) {
        
        pulldownTipView.text = count == 0 ? "没有微博更新" : "更新了 \(count) 条微博"
    
        UIView.animateWithDuration(0.75, animations: { () -> Void in
            
            self.pulldownTipView.frame.origin.y = 44
            
            }) { (_) -> Void in
                
                //延时0.25秒后再退回去
               UIView.animateWithDuration(0.75, delay: 0.25, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                
                self.pulldownTipView.frame.origin.y = -64
                
                }, completion: { (_) -> Void in
                    
                    //从父控件移除
                    self.pulldownTipView.removeFromSuperview()
               })
        }
    }
    
    //MARK: - 加载微博数据
    func loadStatuses() {
        
        //一开始默认是下拉刷新 第一次微博模型数组没有数据，默认加载20条微博
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        
        //菊花正在旋转 说明是上拉加载
        if activity.isAnimating() {
        
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        
        ZDStatus.loadStatuses(since_id, max_id: max_id) { (list, error) -> Void in
            
            //加载微博数据完成  停止刷新
            self.refreshControl?.endRefreshing()
            
            //加载微博数据完成 停止上拉刷新菊花
            self.activity.stopAnimating()
            
            if error != nil {
                
                print(error)
            
                SVProgressHUD.showErrorWithStatus("加载微博数据失败", maskType: SVProgressHUDMaskType.Black)
                
                return
            }
            
            if list == nil {
            
                SVProgressHUD.showInfoWithStatus("没有微博更新", maskType: SVProgressHUDMaskType.Black)
                
                return
            }
            
            let count = list?.count ?? 0
            
            if since_id > 0 {
            
                self.showPulldownTipView(count)
                
                print("下拉刷新加载到 \(count) 条微博")
                //将下拉加载到的微博数据 插入到 当前微博模型数组的前面
                self.statuses = list! + self.statuses!
                
            }else if max_id > 0 {
            
                print("上拉刷新加载到 \(count) 条微博")
                self.statuses = self.statuses! + list!
                
            }else {
                
                print("第一次刷新加载到 \(count) 条微博")
                //第一次加载到20条微博数据
                self.statuses = list!
            }
        }
    }
    
    
    //MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        
        //这里必须要注册cell 否则强制拆包出错
        let cell = tableView.dequeueReusableCellWithIdentifier(status.identifier) as! ZDStatusCell
        
        if cell.delegate == nil {
        
            cell.delegate = self
        }
        
        cell.status = status
        
        //最后一个cell 自动上拉加载更多  过滤重复上拉刷新
        if indexPath.row == (statuses?.count)!-1 && !activity.isAnimating() {
        
            //菊花开始旋转
            activity.startAnimating()
            
            //加载数据
            loadStatuses()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
//        let cell = tableView.cellForRowAtIndexPath(indexPath) as! ZDStatusCell
        
        let status = statuses![indexPath.row]
        
        if let rowHight = status.rowHight {
            
//            print("从缓存加载行高\(indexPath.row)")
        
            return rowHight
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(status.identifier) as! ZDStatusCell
        
        let rowHight = cell.rowHight(status)
        
//        print("计算行高\(indexPath.row)")
        //混存行高
        status.rowHight = rowHight
        
        return rowHight
    }
    
    
    
    //MARK: - 懒加载
    private lazy var activity: UIActivityIndicatorView = {
    
    
        let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        activity.color = UIColor.grayColor()
        
        return activity
    }()
    
    
    //MARK: - 下拉刷新完成后提示view
    private lazy var pulldownTipView: UILabel = {
    
        let label = UILabel()
        
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
    
        return label
    }()
    
    
//    //MARK: - 懒加载图片查看器控制器
//    private lazy var photoBrowserVC: ZDPhotoBrowserViewController = {
//    
//        let vc = ZDPhotoBrowserViewController()
//        
////        self.addChildViewController(vc)  //增加这句代码 modal失败 Application tried to present modally an active controller <_026SwiftSinaWeiBo.ZDHomeViewController: 0x7f9fe3443a60>.
//        
//        return vc
//    }()
}


//MARK: - 转场动画
extension ZDHomeViewController: UIViewControllerTransitioningDelegate {

    /**
     展现控制器 控制显示的对象  指定modal出来的对象的一些属性 并不做动画
     
     :param: presented  modal的控制器
     :param: presenting <#presenting description#>
     :param: source     根控制器
     
     :returns: 返回展现控制器
     */
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        return ZDPresentationController(presentedViewController: presented, presentingViewController: presenting)
    }
    
    ///指定控制器modal时的动画对象  做动画
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        //返回执行动画对象  只要遵守UIViewControllerAnimatedTransitioning协议即可
        return ZDModalAnimation()
    }
    
    ///指定控制器dismiss时的动画对象  做动画
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        return ZDDismissAnimation()
    }
    
}


extension ZDHomeViewController: ZDStatusCellDelegate {

    func urlClick(url: NSURL) {
        
        let webVC = ZDHomeWebViewController()
        
        webVC.url = url
        
        webVC.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(webVC, animated: true)
    }
}
